import os
import re
from src.ui.i18n import _


def format_srt_file_standalone(file_path):
    """
    Formats the specified SRT file using Python code.
    This function performs the following operations:
    1. Replaces '\\h\\n' with a space.
    2. Replaces '\\h' with a space.

    :param file_path: The path to the SRT file to be formatted.
    :return: A tuple (bool, str) indicating success status and a message.
    """
    try:
        # Create backup file path
        backup_path = f"{file_path}.bak"
        
        # To prevent overwriting previous backups, delete if it already exists
        if os.path.exists(backup_path):
            os.remove(backup_path)
            
        # Read original file content
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
        # Perform replacement, order is important
        # Must replace the one with a newline first, then the single one
        # Use regex for replacement to match \h followed by an optional newline
        new_content = re.sub(r'\\h\n?', ' ', content)
        
        # If content has not changed, no need to continue
        if new_content == content:
            return True, _("File '{}' requires no changes.").format(os.path.basename(file_path))
            
        # Create backup
        os.rename(file_path, backup_path)
        
        # Write modified content
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
            
        return True, _("File '{}' has been successfully formatted.").format(os.path.basename(file_path))

    except Exception as e:
        # If an error occurs, try to restore from backup
        if os.path.exists(backup_path):
            try:
                os.rename(backup_path, file_path)
            except Exception as restore_e:
                return False, _("Formatting failed and restoring backup also failed: {}").format(restore_e)
        return False, _("Error while formatting file: {}").format(e)


def format_timestamp(seconds):
    """Formats seconds into an SRT timestamp format 00:00:00,000."""
    # Calculate hours, minutes, seconds, and milliseconds
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    millis = int((seconds - int(seconds)) * 1000)
    
    # 格式化为两位数
    return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"

def format_seconds(seconds):
    """Formats seconds into a readable HH:MM:SS format."""
    seconds = int(seconds)
    hours = seconds // 3600
    minutes = (seconds % 3600) // 60
    secs = seconds % 60
    return f"{hours:02d}:{minutes:02d}:{secs:02d}"

import os
import re

def get_track_title(file_path):
    """
    Generates a track title based on the file path for UI display.
    - If the filename has a language code suffix (e.g., .zh-CN), returns '[zh-CN]'.
    - Otherwise, returns the filename without extension, e.g., '[my_video]'.
    """
    base_name = os.path.splitext(os.path.basename(file_path))[0]
    
    # Regex to find language codes like .en or .en-US at the end of the filename
    lang_code_pattern = re.compile(r'\.([a-z]{2,3}(-[A-Z]{2})?)$')
    
    match = lang_code_pattern.search(base_name)
    if match:
        lang_code = match.group(1)
        return f"[{lang_code}]"
    else:
        return f"[{base_name}]"

def get_language_code_from_path(file_path):
    """
    Extracts the BCP 47 language code from a file path.
    - If a language code like .zh-CN is found, returns 'zh-CN'.
    - Otherwise, returns 'und' (Undetermined).
    """
    base_name = os.path.splitext(os.path.basename(file_path))[0]
    
    # Regex to find language codes like .en or .en-US at the end of the filename
    lang_code_pattern = re.compile(r'\.([a-z]{2,3}(-[A-Z]{2})?)$')
    
    match = lang_code_pattern.search(base_name)
    if match:
        return match.group(1)
    else:
        return "und"
